<?php

namespace StudyBuddy\Forms;

use \StudyBuddy\String\HTMLString;

/**
 * Class responsible
 * for processing the "Ask" form
 *
 */
class Askform extends Form {

    /**
     * Name of form template file
     * The name of actual template should be
     * set in sub-class
     *
     * @var string
     */
    protected $template = 'tplFormask';

    protected function init() {

        /**
         * This is just an example how a custom validation
         * callback could be added to form
         * The callback must accept value of element
         * and must return error string or true
         * if there are no errors
         *
         * @see Form::init()
         */
        /* $this->addValidator('title', function($val){

          if(\mb_strlen($val) < 1){
          return 'Title must contain at least 1 character long';
          }

          return true;
          }); */

        $minTags = $this->oRegistry->Ini->MIN_QUESTION_TAGS;
        $maxTags = $this->oRegistry->Ini->MAX_QUESTION_TAGS;

        $d = $this->Tr->get('Please enter between {min_tags} and {max_tags} tags, separated by comma', array('{min_tags}' => $minTags, '{max_tags}' => $maxTags));
        $this->setVar('tags_d', $d);
        $this->setVar('tags_l', $this->Tr['Tags']);
        $this->setVar('Preview', $this->Tr['Preview']);
        $this->setVar('Preview', $this->Tr['Preview']);
        $this->setVar('title_d', $this->Tr['Enter a descriptive title']);
        $this->setVar('title_l', $this->Tr['Title']);
        $this->setVar('submit', $this->Tr['Ask Question']);

        $this->setVar('level', $this->buildSec());
//        $this->setVar('subject', $this->buildSubject());
        if($this->oRegistry->Viewer->isAdmin()) {
            $this->setVar('dif', $this->buildDif());
        } else {
            $this->setVar('dif', '<input type="hidden" value="" name="dif" />');
        }

        if ($minTags > 0) {
            $tagsRequired = '(* %s)';
            $this->setVar('tags_required', sprintf($tagsRequired, 'required'));
        }

        $minTitle = $this->oRegistry->Ini->MIN_TITLE_CHARS;
        if ($minTitle > 0) {
            $t = 'Please enter a descriptive title at least %s characters long';
            $this->setVar('title_d', sprintf($t, $minTitle));
        }
    }

    /**
     * Concrete form validator for this form
     * (non-PHPdoc)
     * @see Form::doValidate()
     */
    protected function doValidate() {

        $this->validateBody()->validateTitle()->validateTags();
    }

    /**
     * Validate title length
     *
     * @return object $this
     */
    protected function validateTitle() {
        $t = $this->oRegistry->Request['title'];
        $min = $this->oRegistry->Ini->MIN_TITLE_CHARS;
        d('min title: ' . $min);
        if (\mb_strlen($t) < $min) {
            $this->setError('title', 'Title must contain at least ' . $min . ' letters');
        }

        return $this;
    }

    /**
     * Validate min number of words in question
     * and min number of chars in question
     *
     * @return object $this
     */
    protected function validateBody() {

        $minChars = $this->oRegistry->Ini->MIN_QUESTION_CHARS;
        $minWords = $this->oRegistry->Ini->MIN_QUESTION_WORDS;
        $body = $this->oRegistry->Request->getUTF8('qbody');
        $oHtmlString = HTMLString::factory($body);
        $wordCount = $oHtmlString->getWordsCount();
        $len = $oHtmlString->length();

        if ($len < $minChars) {
            /**
             * @todo Translate string
             */
            $this->setError('qbody', 'Question must contain at least ' . $minChars . ' letters');
        }


        if ($wordCount < $minWords) {
            /**
             * @todo Translate string
             */
            $this->setError('qbody', 'Question must contain at least ' . $minWords . ' words');
        }

        return $this;
    }

    /**
     * Validate to enforce at least one tag
     * and not more that value MAX_QUESTION_TAGS in settings
     *
     * @return object $this
     */
    protected function validateTags() {
        $min = $this->oRegistry->Ini->MIN_QUESTION_TAGS;
        $max = $this->oRegistry->Ini->MAX_QUESTION_TAGS;
        $tags = $this->oRegistry->Request->get('tags', 's', '');
        $tags = \trim($tags);
        /* if(($min > 0) && empty($tags)){
          $this->setError('tags', 'You must include at least one tag');
          } */

        \mb_regex_encoding('UTF-8');
        $aTags = \mb_split('([,;]+)', $tags);
        $count = count($aTags);

        if ($count > $max) {
            /**
             * @todo Translate string
             */
            $this->setError('tags', 'Question cannot have more than ' . $max . ' tags. Please remove some tags');
        }

        if ($count < $min) {
            /**
             * @todo Translate string
             */
            $this->setError('tags', 'Question must have at least ' . ($min-1) . ' tag(s)');
        }

        return $this;
    }

    protected function buildSec() {
        $s = '';
        $current = '';
        $sec = array(
            1 => 'Sec 1',
            2 => 'Sec 2',
            3 => 'Sec 3&4'
        );

        $tpl = '<option value="%1$s"%2$s>%3$s</option>';
        foreach ($sec as $key => $val) {
            $selected = ($key == $current) ? ' selected="selected"' : '';
            $s .= vsprintf($tpl, array($key, $selected, $val));
        }

        return $s;
    }

    protected function buildSubject() {
        $s = '';
        $current = '';
        $subject = array(
            1 => 'E Maths',
            2 => 'A Maths',
            3 => 'Physics'
        );

        $tpl = '<option value="%1$s"%2$s>%3$s</option>';
        foreach ($subject as $key => $val) {
            $selected = ($key == $current) ? ' selected="selected"' : '';
            $s .= vsprintf($tpl, array($key, $selected, $val));
        }

        return $s;
    }

    protected function buildDif() {
        $s = '';
        $current = '';
        $dif = array(
            1 => '1',
            2 => '2',
            3 => '3',
            4 => '4',
            5 => '5'
        );

        $tpl = '<option value="%1$s"%2$s>%3$s</option>';
        foreach ($dif as $key => $val) {
            $selected = ($key == $current) ? ' selected="selected"' : '';
            $s .= vsprintf($tpl, array($key, $selected, $val));
        }
        $s = '<div class="ctl-nav-solid">
                <img alt="" src="/images/2/icon/solid.gif" />
            </div>
            <div class="ctl-nav-ct" style="position:relative">	                            
                <select name="dif" style="border:none; background:#ff8e33; padding:0 3px 3px 0; width:86px; position:relative">
                    <option value="">Difficult</option>
                    '.$s.'
                </select>
                <span style="position:absolute; float:right; bottom:0; right:0; width:24px; height:24px; background-color:#ff8e33"></span>
            </div>';

        return $s;
    }
}
